import { UnorderedListOutlined, UploadOutlined } from "@ant-design/icons"
import type { CheckboxOptionType } from "antd"
import { Button, Checkbox, Modal, Space } from "antd"
import { clone } from "lodash"
import React, { useState } from "react"
import { useDispatch } from "react-redux"

import { useLocale } from "@/locales"
import { updateNotices } from "@/stores/user/user.action"

// import { setAnimateDownload } from "@/stores/app/app.store"
import CommonModal from "../modals"

interface ToolbarProps {
	columns: any[]
	onExport?: () => void
	changeColumns: (columns: any[]) => void
	showRowSet?: boolean // 是否显示列设置
}

const getAllColumns = (columns: any[]) => {
	const allColumns: any[] = []
	function loop(column: any[]) {
		const length = column.length
		for (let i = 0; i < length; i++) {
			const item = column[i]
			allColumns.push(item)
			if (item.children) {
				loop(item.children)
			}
		}
	}
	loop(columns)
	return allColumns
}
type Column = {
	dataIndex?: string
	key?: string
	hidden?: boolean
	children?: Column[]
}

const formatColumns = (columns: Column[], checkedList: string[]): Column[] => {
	function loop(column: any[]) {
		const length = column.length
		for (let i = 0; i < length; i++) {
			const item = column[i]
			item.hidden = !checkedList.includes(item.dataIndex || item.key)
			if (item.children) {
				item.children = loop(item.children)
			}
		}
		return column
	}
	return loop(columns)
}

const getTitle = (title: string | React.ReactElement | (() => React.ReactElement)) => {
	return typeof title === "function" ? title() : title
}

const Toolbar: React.FC<ToolbarProps> = (props: ToolbarProps) => {
	const { columns, onExport, changeColumns, showRowSet } = props
	const { newFormat, formatMessage } = useLocale()
	const dispatch = useDispatch()
	const allColumns = getAllColumns(columns)

	const defaultCheckedList = allColumns.filter(item => !item.hidden).map(item => item.dataIndex || item.key)

	const [open, setOpen] = useState(false)

	const [checkedList, setCheckedList] = useState(defaultCheckedList)

	const options: CheckboxOptionType<any>[] = allColumns.map(({ key, titleText, dataIndex, title }) => ({
		// titleText换成title可以是拖拽
		label: titleText || getTitle(title) || dataIndex,
		value: dataIndex || key
	}))

	const onChange = (v: any) => {
		if (v.length <= 0) {
			return false
		}
		setCheckedList(v)
	}

	const close = () => {
		setOpen(false)
		setCheckedList(allColumns.filter(item => !item.hidden).map(item => item.dataIndex || item.key))
	}

	const ok = () => {
		const _columns = clone(columns)
		const _columnsOrder = formatColumns(_columns, checkedList)
		changeColumns(_columnsOrder)
		setOpen(false)
	}

	const handleCheckedAllFieldColumn = () => {
		const checked = allColumns.map(item => item.dataIndex || item.key)
		setCheckedList(checked)
	}

	return (
		<Space style={{ float: "right" }}>
			{onExport && (
				<UploadOutlined
					onClick={() => {
						Modal.confirm({
							title: formatMessage({ id: "label.member.export_excel_confirm" }),
							content: formatMessage({ id: "label.member.export_excel_confirm_context" }),
							onOk: async () => {
								const ret = (await onExport()) as unknown as boolean
								if (ret) dispatch(updateNotices())
							},
							footer: (_, { OkBtn, CancelBtn }) => (
								<>
									<CancelBtn />
									<OkBtn />
								</>
							)
						})
					}}
					title={newFormat("common.export")}
					style={{ marginRight: "30px", fontSize: "20px" }}
				/>
			)}
			<></>
			{showRowSet && (
				<UnorderedListOutlined
					style={{ fontSize: "20px" }}
					onClick={() => {
						setOpen(true)
					}}
				/>
			)}
			<CommonModal title={formatMessage({ id: "common.column_setting" })} open={open} onCancel={close} onOk={ok} destroyOnClose>
				<Button onClick={handleCheckedAllFieldColumn}>{formatMessage({ id: "funds.filter_table.reset_filter" })}</Button>
				<Checkbox.Group
					style={{ display: "flex", flexDirection: "column" }}
					value={checkedList}
					options={options}
					onChange={onChange}
				/>
			</CommonModal>
		</Space>
	)
}

export default Toolbar
